package com.zxd.interview.export;

import com.zxd.interview.constant.QualityConstants;
import com.zxd.interview.export.dto.TestReportDTO;
import com.zxd.interview.service.IQualityReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * word导出控制器
 *
 * @author zhaoxudong
 * @version 1.0
 * @date 2020/11/7 12:51
 */
@Controller
public class WordExportController {

    @Autowired
    private IQualityReportService qualityReportService;

    /**
     * 生成报告的导出报表操作
     *
     * @param request           request
     * @param response          响应数据
     * @param testReportDTO 导出dto
     */
    @PostMapping("/quality/exportword")
    @ResponseBody
    public void povertyExportWord(HttpServletRequest request, HttpServletResponse response,
                                    TestReportDTO testReportDTO) {

        File file = qualityReportService.expoortTestFile(testReportDTO);

        InputStream fin = null;
        OutputStream out = null;
        try {
            // 调用工具类WordGeneratorUtils的createDoc方法生成Word文档
            fin = new FileInputStream(file);

            response.setCharacterEncoding(QualityConstants.UTF_8);
            response.setContentType(QualityConstants.CONTENT_TYPE_WORD);
            // 设置浏览器以下载的方式处理该文件
            // 设置文件名编码解决文件名乱码问题
            //获得请求头中的User-Agent
            String filename = testReportDTO.getWordName();
            String agent = request.getHeader(QualityConstants.USER_AGENT);
            String filenameEncoder = "";
            // 根据不同的浏览器进行不同的判断
            if (agent.contains(QualityConstants.MSIE)) {
                // IE浏览器
                filenameEncoder = URLEncoder.encode(filename, QualityConstants.UTF_8);
                filenameEncoder = filenameEncoder.replace("+", " ");
            } else if (agent.contains(QualityConstants.FIREFOX)) {
                // 火狐浏览器
                // 高版本JDK替换
                Base64.Encoder base64Encoder = Base64.getEncoder();
                filenameEncoder = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes(StandardCharsets.UTF_8)) + "?=";
            } else {
                // 其它浏览器
                filenameEncoder = URLEncoder.encode(filename, QualityConstants.UTF_8);
            }
            response.setHeader(QualityConstants.ACCESS_CONTROL_ALLOW_ORIGIN, "*");//所有域都可以跨
            response.setHeader(QualityConstants.CONTENT_TYPE, QualityConstants.CONTENT_TYPE_STEAM);//二进制  流文件
            response.setHeader(QualityConstants.CONTENT_DISPOSITION, "attachment;filename=" + filenameEncoder + ".doc");//下载及其文件名
            response.setHeader(QualityConstants.CONNECTION, QualityConstants.CLOSE);//关闭请求头连接
            //设置文件在浏览器打开还是下载
            response.setContentType(QualityConstants.CONTENT_TYPE_DOWNLOAD);
            out = response.getOutputStream();
            byte[] buffer = new byte[QualityConstants.BYTE_512];
            int bytesToRead = QualityConstants.NUM_MINUS_1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != QualityConstants.NUM_MINUS_1) {
                out.write(buffer, QualityConstants.NUM_ZERO, bytesToRead);
            }

        } catch (Exception e) {
            throw new RuntimeException(QualityConstants.FARIURE_EXPORT, e);
        } finally {
            try {
                if (fin != null) {
                    fin.close();
                }
                if (out != null) {
                    out.close();
                }
                if (file != null) {
                    file.delete();
                }
            } catch (IOException e) {
                throw new RuntimeException(QualityConstants.FARIURE_EXPORT, e);
            }
        }

    }


}

